package com.weilai.controller;

import com.weilai.controller.exceptionHandler.BusinessException;
import com.weilai.controller.exceptionHandler.Code;
import com.weilai.controller.exceptionHandler.SystemException;
import com.weilai.domain.User;
import com.weilai.service.CaptchaService;
import com.weilai.service.EmailService;
import com.weilai.service.UserService;
import com.weilai.util.PasswordUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

@Api(tags = "修改密码", description = "提供在个人主页修改密码方法的接口")
@RestController
@RequestMapping("/updatePassword")
public class UpdatePasswordController {

    @Autowired
    private CaptchaService captchaService;

    @Autowired
    private UserService userService;

    @Autowired
    private EmailService emailService;

    @ApiOperation(value = "跳转修改密码页面方法", notes = "在修改密码之前需要直接获取用户邮箱，" +
            "这个方法在跳转的通知会传递给前端一个邮箱，不需要用户重复输入了")
    //当点击修改密码跳转页面时，传递登录者邮箱
    @GetMapping
    public ModelAndView showUpdatePasswordPage(HttpServletRequest request) {
        try {
            ModelAndView mav = new ModelAndView();
            HttpSession session = request.getSession(false);

            // 检查会话是否存在
            if (session == null || session.getAttribute("userId") == null) {
                throw new BusinessException(Code.PROJECT_ACCESS_DENIED, "请先登录");
            }

            int id = (int) session.getAttribute("userId");
            User user = userService.getUserById(id);

            // 检查用户是否存在
            if (user == null) {
                throw new BusinessException(Code.PROJECT_DATA_NOT_FOUND, "用户不存在");
            }

            mav.addObject("userId", id);
            mav.addObject("email", user.getEmail());
            mav.setViewName("accountSetting");
            return mav;
        } catch (BusinessException e) {
            throw e;
        } catch (Exception e) {
            throw new SystemException(Code.SYSTEM_UNKNOWN_ERROR, "获取用户信息失败", e);
        }
    }

    @ApiOperation(value = "验证验证码", notes = "校验用户输入的验证码是否正确")
    @PostMapping("/verify")
    @ResponseBody
    public ResponseEntity<?> verify(@RequestParam String code, HttpServletRequest request) {
        try {

            HttpSession session = request.getSession(false);

            // 检查会话是否存在
            if (session == null || session.getAttribute("userId") == null) {
                throw new BusinessException(Code.PROJECT_ACCESS_DENIED, "请先登录");
            }

            int id = (int) session.getAttribute("userId");
            User user = userService.getUserById(id);

            // 1. 校验验证码是否为空
            if (code == null || code.trim().isEmpty()) {
                throw new BusinessException(Code.PROJECT_VALIDATE_ERROR, "验证码不能为空");
            }

            // 2. 校验验证码是否正确
            if (captchaService.getByEamil(user.getEmail())==null || !code.equals(String.valueOf(captchaService.getByEamil(user.getEmail()).getCaptchaCode()))) {
                throw new BusinessException(Code.PROJECT_VALIDATE_ERROR, "验证码错误，请重试");
            }

            // 3. 验证成功，返回 JSON 响应
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("message", "验证成功");
            return ResponseEntity.ok(result);

        } catch (BusinessException e) {
            // 业务异常直接抛出（由全局异常处理器处理）
            throw e;
        } catch (Exception e) {
            // 系统异常封装后抛出
            throw new SystemException(Code.SYSTEM_UNKNOWN_ERROR, "验证码验证失败", e);
        }
    }

    @ApiOperation(value = "修改密码方法", notes = "修改密码方法，需要输入验证码、新密码")
    @PostMapping("/update")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> updatePassword(
            @RequestParam String newPassword,
            HttpServletRequest request) {

        Map<String, Object> response = new HashMap<>();
        try {
            // 1. 参数校验
            if (newPassword == null || newPassword.trim().isEmpty()) {
                throw new BusinessException(Code.PROJECT_VALIDATE_ERROR, "新密码不能为空");
            }

            HttpSession session = request.getSession(false);

            // 2. 检查会话
            if (session == null || session.getAttribute("userId") == null) {
                throw new BusinessException(Code.PROJECT_ACCESS_DENIED, "会话已过期，请重新登录");
            }

            int id = (int) session.getAttribute("userId");
            User user = userService.getUserById(id);

            // 3. 检查用户
            if (user == null) {
                throw new BusinessException(Code.PROJECT_DATA_NOT_FOUND, "用户不存在");
            }

            // 5. 密码校验逻辑
//            if (PasswordUtil.matches(newPassword, user.getPassword())) {
//                throw new BusinessException(Code.PROJECT_BUSINESS_ERROR, "不能使用之前设置过的密码");
//            }
            if (!newPassword.equals(user.getPassword())) {
                throw new BusinessException(Code.PROJECT_BUSINESS_ERROR, "不能使用之前设置过的密码");
            }

            if (newPassword.length() < 6 || newPassword.length() > 20) {
                throw new BusinessException(Code.PROJECT_VALIDATE_ERROR, "密码长度需在6-20位之间");
            }

            if (!newPassword.matches(".*[a-zA-Z].*")) {
                throw new BusinessException(Code.PROJECT_VALIDATE_ERROR, "密码必须包含字母");
            }

            // 6. 更新密码
//            user.setPassword(PasswordUtil.encode(newPassword));
            user.setPassword(newPassword);
            userService.updateUser(user);

            // 7. 返回成功响应（不再跳转页面）
            response.put("success", true);
            response.put("message", "密码修改成功");
            response.put("redirectUrl", "/login");
            return ResponseEntity.ok(response);

        } catch (BusinessException e) {
            throw e; // 由全局异常处理器处理
        } catch (Exception e) {
            throw new SystemException(Code.SYSTEM_UNKNOWN_ERROR, "修改密码失败", e);
        }
    }

    @ApiOperation(value = "发送验证码方法", notes = "发送验证码，需要输入用户邮箱")
    @ApiResponses({
            @ApiResponse(code = 200, message = "发送成功")
    })
    //发送验证码
    @PostMapping("/sendCode")
    public ModelAndView sendCode(@RequestParam String email) {
        try {
            ModelAndView mav = new ModelAndView();

            //发送验证码
            captchaService.sendCode(email);

            mav.addObject("result", "验证码已发送至您的邮箱");
            mav.setViewName("accountSetting");
            return mav;
        } catch (BusinessException e) {
            throw e;
        } catch (Exception e) {
            throw new SystemException(Code.SYSTEM_UNKNOWN_ERROR, "发送验证码失败", e);
        }
    }
}
